<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>局域网文件共享</title>
    <link rel="icon" href="/static/logo.ico" type="image/x-icon">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            text-align: center;
            color: white;
            margin-bottom: 30px;
        }

        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
        }

        .header p {
            font-size: 1.1rem;
            opacity: 0.9;
        }

        .file-browser {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            overflow: hidden;
        }

        .browser-header {
            background: #f8f9fa;
            padding: 20px;
            border-bottom: 1px solid #e9ecef;
        }

        .current-path {
            display: flex;
            align-items: center;
            gap: 10px;
            font-family: monospace;
            color: #495057;
        }

        .path-icon {
            font-size: 1.2rem;
        }

        .file-list {
            max-height: 600px;
            overflow-y: auto;
        }

        .file-item {
            display: flex;
            align-items: center;
            padding: 15px 20px;
            border-bottom: 1px solid #f0f0f0;
            text-decoration: none;
            color: #333;
            transition: all 0.2s ease;
            cursor: pointer;
        }

        .file-item:hover {
            background: #dfefff;
        }

        .file-item:last-child {
            border-bottom: none;
        }

        .file-icon {
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            margin-right: 15px;
        }

        .file-info {
            flex: 1;
        }

        .file-name {
            font-weight: 500;
            font-size: 1rem;
            margin-bottom: 2px;
        }

        .file-meta {
            font-size: 0.85rem;
            color: #6c757d;
            display: flex;
            gap: 15px;
        }

        .directory .file-name {
            color: #007bff;
            font-weight: 600;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #6c757d;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #6c757d;
        }

        .empty-state .icon {
            font-size: 3rem;
            margin-bottom: 15px;
            opacity: 0.5;
        }

        .upload-area {
            background: #f8f9fa;
            border: 2px dashed #dee2e6;
            border-radius: 10px;
            padding: 20px;
            margin: 20px;
            text-align: center;
            color: #6c757d;
            transition: all 0.3s ease;
        }

        .upload-area.drag-over {
            border-color: #007bff;
            background: #e3f2fd;
            color: #007bff;
        }

        .upload-controls {
            display: flex;
            gap: 10px;
            margin: 15px 0;
            justify-content: center;
            flex-wrap: wrap;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.2s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }

        .btn-primary {
            background: #007bff;
            color: white;
        }

        .btn-primary:hover {
            background: #0056b3;
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn-success:hover {
            background: #1e7e34;
        }

        .btn-danger {
            background: #dc3545;
            color: white;
        }

        .btn-danger:hover {
            background: #c82333;
        }

        .file-actions {
            display: flex;
            gap: 5px;
            margin-left: 10px;
        }

        .file-actions .btn {
            padding: 4px 8px;
            font-size: 12px;
        }

        .progress-bar {
            width: 100%;
            height: 4px;
            background: #e9ecef;
            border-radius: 2px;
            overflow: hidden;
            margin: 10px 0;
        }

        .progress-fill {
            height: 100%;
            background: #007bff;
            width: 0%;
            transition: width 0.3s ease;
        }

        .modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1000;
        }

        .modal.hidden {
            display: none !important;
        }

        .hidden {
            display: none !important;
        }

        .modal-content {
            background: white;
            padding: 20px;
            border-radius: 10px;
            max-width: 400px;
            width: 90%;
        }

        .modal-content h3 {
            margin-top: 0;
        }

        .modal-content input {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin: 10px 0;
        }

        .stats {
            background: rgba(255, 255, 255, 0.1);
            color: white;
            padding: 15px 20px;
            margin-bottom: 20px;
            border-radius: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            backdrop-filter: blur(10px);
        }

        .refresh-indicator {
            position: fixed;
            top: 20px;
            right: 20px;
            background: rgba(0, 123, 255, 0.9);
            color: white;
            padding: 8px 12px;
            border-radius: 20px;
            font-size: 12px;
            z-index: 999;
            display: flex;
            align-items: center;
            gap: 5px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .refresh-indicator:hover {
            background: rgba(0, 123, 255, 1);
        }

        .refresh-indicator.disabled {
            background: rgba(108, 117, 125, 0.9);
            cursor: pointer;
        }

        .refresh-dot {
            width: 8px;
            height: 8px;
            background: #fff;
            border-radius: 50%;
            animation: pulse 1s infinite;
        }

        .refresh-indicator.disabled .refresh-dot {
            animation: none;
            opacity: 0.5;
        }

        @keyframes pulse {

            0%,
            100% {
                opacity: 1;
            }

            50% {
                opacity: 0.3;
            }
        }

        .stat-item {
            text-align: center;
        }

        .stat-number {
            font-size: 1.5rem;
            font-weight: bold;
            display: block;
        }

        .stat-label {
            font-size: 0.85rem;
            opacity: 0.8;
        }

        @media (max-width: 768px) {
            .header h1 {
                font-size: 2rem;
            }

            .file-meta {
                flex-direction: column;
                gap: 5px;
            }

            .stats {
                flex-direction: column;
                gap: 10px;
            }

            .stat-item {
                display: flex;
                align-items: center;
                gap: 10px;
            }
        }
    </style>
</head>

<body>
    <!-- 实时刷新指示器 -->
    <div id="refreshIndicator" class="refresh-indicator disabled" onclick="toggleAutoRefresh()" title="点击切换自动刷新">
        <div class="refresh-dot"></div>
        <span>已暂停</span>
    </div>

    <div class="container">
        <div class="header">
            <h1>📁 局域网文件共享</h1>
        </div>

        <div class="stats">
            <div class="stat-item">
                <span class="stat-number" id="fileCount">-</span>
                <span class="stat-label">文件数量</span>
            </div>
            <div class="stat-item">
                <span class="stat-number" id="folderCount">-</span>
                <span class="stat-label">文件夹数量</span>
            </div>
            <div class="stat-item">
                <span class="stat-number" id="totalSize">-</span>
                <span class="stat-label">总大小</span>
            </div>
        </div>

        <div class="file-browser">
            <div class="browser-header">
                <div class="current-path">
                    <span class="path-icon">📂</span>
                    <span id="currentPath">正在加载...</span>
                </div>
            </div>

            <div id="fileList" class="file-list">
                <div class="loading">
                    <div>🔄 正在加载文件列表...</div>
                </div>
            </div>

            <div class="upload-area" id="uploadArea">
                <div>📤 拖拽文件到此处上传，或点击下方按钮选择文件</div>
                <div class="upload-controls">
                    <button class="btn btn-primary" onclick="selectFiles()">📁 选择文件</button>
                    <!-- <button class="btn btn-success" onclick="showCreateFolderModal()">📂 新建文件夹</button> -->
                </div>
                <div id="progressBar" class="progress-bar hidden">
                    <div class="progress-fill" id="progressFill"></div>
                </div>
                <input type="file" id="fileInput" multiple style="display: none;">
            </div>
        </div>
    </div>

    <!-- 新建文件夹模态框 -->
    <div id="createFolderModal" class="modal hidden" onclick="hideCreateFolderModal()">
        <div class="modal-content" onclick="event.stopPropagation()">
            <h3>新建文件夹</h3>
            <input type="text" id="folderNameInput" placeholder="请输入文件夹名称">
            <div class="upload-controls">
                <button class="btn btn-success" onclick="createFolder()">创建</button>
                <button class="btn btn-danger" onclick="hideCreateFolderModal()">取消</button>
            </div>
        </div>
    </div>

    <script>
        let currentPath = '/';

        // 获取文件图标
        function getFileIcon(filename, isDirectory) {
            if (isDirectory) return '📁';

            const ext = filename.split('.').pop().toLowerCase();
            const icons = {
                'png': '🖼️', 'jpg': '🖼️', 'jpeg': '🖼️', 'gif': '🖼️', 'svg': '🖼️',
                'mp4': '🎬', 'avi': '🎬', 'mov': '🎬', 'mkv': '🎬',
                'mp3': '🎵', 'wav': '🎵', 'flac': '🎵',
                'pdf': '📄', 'doc': '📄', 'docx': '📄', 'txt': '📄',
                'zip': '📦', 'rar': '📦', '7z': '📦',
                'js': '⚡', 'html': '🌐', 'css': '🎨', 'json': '📋'
            };
            return icons[ext] || '📄';
        }

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
        }

        // 格式化时间
        function formatDate(dateString) {
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN');
        }

        // 加载文件列表
        async function loadFileList(path = '/') {
            try {
                // 标准化路径
                path = path.replace(/\/+/g, '/'); // 替换多个连续斜杠为单个斜杠
                if (path !== '/' && path.endsWith('/')) {
                    path = path.slice(0, -1); // 移除末尾斜杠（根路径除外）
                }

                console.log('Loading path:', path); // 调试信息

                const response = await fetch(`/api/files${path}`);
                const data = await response.json();

                console.log('Response data:', data); // 调试信息

                displayFileList(data.files, path);
                updateStats(data.stats);
                updateCurrentPath(path);

            } catch (error) {
                console.error('加载文件列表失败:', error);
                document.getElementById('fileList').innerHTML = `
                    <div class="empty-state">
                        <div class="icon">❌</div>
                        <div>加载文件列表失败</div>
                    </div>
                `;
            }
        }

        // 显示文件列表
        function displayFileList(files, path) {
            const fileListContainer = document.getElementById('fileList');

            let html = '';

            // 添加返回上级目录选项（即使文件夹为空也显示）
            if (path !== '/') {
                let parentPath = '/';
                const pathParts = path.split('/').filter(part => part !== '');
                if (pathParts.length > 1) {
                    parentPath = '/' + pathParts.slice(0, -1).join('/');
                }
                console.log('Current path:', path, 'Parent path:', parentPath); // 调试信息

                html += `
                    <div class="file-item" onclick="loadFileList('${parentPath}')">
                        <div class="file-icon">📁</div>
                        <div class="file-info">
                            <div class="file-name">..</div>
                            <div class="file-meta">
                                <span>返回上级目录</span>
                            </div>
                        </div>
                    </div>
                `;
            }

            // 显示文件和文件夹
            files.forEach(file => {
                const icon = getFileIcon(file.name, file.isDirectory);
                const className = file.isDirectory ? 'directory' : '';
                const onclick = file.isDirectory
                    ? `loadFileList('${file.path}')`
                    : `window.open('${file.path}', '_blank')`;

                html += `
                    <div class="file-item ${className}">
                        <div class="file-icon">${icon}</div>
                        <div class="file-info" onclick="${onclick}">
                            <div class="file-name">${file.name}</div>
                            <div class="file-meta">
                                <span>${file.isDirectory ? '文件夹' : formatFileSize(file.size)}</span>
                                <span>${formatDate(file.modified)}</span>
                            </div>
                        </div>
                        <div class="file-actions">
                            <button class="btn btn-danger" style="display: none;" onclick="deleteFile('${file.path}', '${file.name}', event)">🗑️</button>
                        </div>
                    </div>
                `;
            });

            // 如果没有文件，显示空状态提示
            if (files.length === 0 && path === '/') {
                html += `
                    <div class="empty-state">
                        <div class="icon">📂</div>
                        <div>此文件夹为空</div>
                        <div style="margin-top: 10px; font-size: 0.9rem;">可以上传文件或创建文件夹</div>
                    </div>
                `;
            } else if (files.length === 0) {
                html += `
                    <div class="empty-state">
                        <div class="icon">📂</div>
                        <div>此文件夹为空</div>
                        <div style="margin-top: 10px; font-size: 0.9rem;">可以上传文件或创建文件夹</div>
                    </div>
                `;
            }

            fileListContainer.innerHTML = html;
        }

        // 更新统计信息
        function updateStats(stats) {
            document.getElementById('fileCount').textContent = stats.fileCount || 0;
            document.getElementById('folderCount').textContent = stats.folderCount || 0;
            document.getElementById('totalSize').textContent = formatFileSize(stats.totalSize || 0);
        }

        // 更新当前路径
        function updateCurrentPath(path) {
            currentPath = path;
            document.getElementById('currentPath').textContent = path === '/' ? '根目录' : path;
        }

        // 实时更新定时器
        let autoRefreshTimer = null;
        let isAutoRefreshEnabled = false;
        let isUserInteracting = false;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function () {
            loadFileList('/');
            setupUploadEvents();
            startAutoRefresh();
        });

        // 开始自动刷新
        function startAutoRefresh() {
            if (autoRefreshTimer) {
                clearInterval(autoRefreshTimer);
            }

            autoRefreshTimer = setInterval(() => {
                if (isAutoRefreshEnabled && !document.hidden && !isUserInteracting) {
                    console.log('自动刷新文件列表，当前路径:', currentPath);
                    refreshFileList();
                }
            }, 1000); // 每秒刷新一次
        }

        // 停止自动刷新
        function stopAutoRefresh() {
            if (autoRefreshTimer) {
                clearInterval(autoRefreshTimer);
                autoRefreshTimer = null;
            }
        }

        // 刷新当前文件列表（不改变路径）
        async function refreshFileList() {
            try {
                // 标准化路径
                let path = currentPath.replace(/\/+/g, '/');
                if (path !== '/' && path.endsWith('/')) {
                    path = path.slice(0, -1);
                }

                const response = await fetch(`/api/files${path}`);
                const data = await response.json();

                // 静默更新，不显示加载状态
                displayFileList(data.files, path);
                updateStats(data.stats);

            } catch (error) {
                console.warn('自动刷新失败:', error);
                // 自动刷新失败时不显示错误，避免干扰用户
            }
        }

        // 切换自动刷新状态
        function toggleAutoRefresh() {
            isAutoRefreshEnabled = !isAutoRefreshEnabled;
            const indicator = document.getElementById('refreshIndicator');
            const indicatorText = indicator.querySelector('span');

            if (isAutoRefreshEnabled) {
                indicator.classList.remove('disabled');
                indicatorText.textContent = '实时更新';
                console.log('自动刷新已启用');
                // 立即刷新一次
                refreshFileList();
            } else {
                indicator.classList.add('disabled');
                indicatorText.textContent = '已暂停';
                console.log('自动刷新已禁用');
            }
        }

        // 页面可见性变化时的处理
        document.addEventListener('visibilitychange', function () {
            if (document.hidden) {
                console.log('页面隐藏，暂停自动刷新');
                // 页面隐藏时暂时停用，但不改变用户的设置
            } else {
                console.log('页面显示，恢复自动刷新');
                // 页面重新显示时立即刷新一次（如果启用了自动刷新）
                if (isAutoRefreshEnabled) {
                    refreshFileList();
                }
            }
        });

        // 设置上传相关事件
        function setupUploadEvents() {
            const uploadArea = document.getElementById('uploadArea');
            const fileInput = document.getElementById('fileInput');

            // 拖拽上传
            uploadArea.addEventListener('dragover', (e) => {
                e.preventDefault();
                uploadArea.classList.add('drag-over');
            });

            uploadArea.addEventListener('dragleave', (e) => {
                e.preventDefault();
                uploadArea.classList.remove('drag-over');
            });

            uploadArea.addEventListener('drop', (e) => {
                e.preventDefault();
                uploadArea.classList.remove('drag-over');
                const files = Array.from(e.dataTransfer.files);
                uploadFiles(files);
            });

            // 文件输入变化
            fileInput.addEventListener('change', (e) => {
                const files = Array.from(e.target.files);
                uploadFiles(files);
            });
        }

        // 选择文件
        function selectFiles() {
            document.getElementById('fileInput').click();
        }

        // 上传文件
        async function uploadFiles(files) {
            if (files.length === 0) return;

            console.log('上传文件到路径:', currentPath); // 调试信息

            // 标记用户正在交互
            isUserInteracting = true;

            const formData = new FormData();
            files.forEach(file => {
                formData.append('files', file);
            });
            formData.append('path', currentPath);

            const progressBar = document.getElementById('progressBar');
            const progressFill = document.getElementById('progressFill');

            progressBar.classList.remove('hidden');
            progressFill.style.width = '0%';

            try {
                const xhr = new XMLHttpRequest();

                // 上传进度
                xhr.upload.addEventListener('progress', (e) => {
                    if (e.lengthComputable) {
                        const percentage = (e.loaded / e.total) * 100;
                        progressFill.style.width = percentage + '%';
                    }
                });

                // 上传完成
                xhr.addEventListener('load', () => {
                    progressBar.classList.add('hidden');
                    isUserInteracting = false; // 用户交互结束
                    if (xhr.status === 200) {
                        const result = JSON.parse(xhr.responseText);
                        alert(result.message);
                        refreshFileList(); // 立即刷新文件列表
                    } else {
                        const error = JSON.parse(xhr.responseText);
                        alert('上传失败: ' + error.error);
                    }
                });

                // 上传错误
                xhr.addEventListener('error', () => {
                    progressBar.classList.add('hidden');
                    isUserInteracting = false; // 用户交互结束
                    alert('上传失败，请重试');
                });

                xhr.open('POST', '/api/upload');
                xhr.send(formData);

            } catch (error) {
                progressBar.classList.add('hidden');
                alert('上传失败: ' + error.message);
            }

            // 清空文件输入
            document.getElementById('fileInput').value = '';
        }

        // 显示创建文件夹模态框
        function showCreateFolderModal() {
            document.getElementById('createFolderModal').classList.remove('hidden');
            document.getElementById('folderNameInput').focus();
        }

        // 隐藏创建文件夹模态框
        function hideCreateFolderModal() {
            document.getElementById('createFolderModal').classList.add('hidden');
            document.getElementById('folderNameInput').value = '';
        }

        // 创建文件夹
        async function createFolder() {
            const folderName = document.getElementById('folderNameInput').value.trim();

            if (!folderName) {
                alert('请输入文件夹名称');
                return;
            }

            isUserInteracting = true; // 标记用户正在交互

            try {
                const response = await fetch('/api/mkdir', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        folderName: folderName,
                        path: currentPath
                    })
                });

                const result = await response.json();

                if (response.ok) {
                    alert(result.message);
                    hideCreateFolderModal();
                    refreshFileList(); // 立即刷新文件列表
                } else {
                    alert('创建失败: ' + result.error);
                }

            } catch (error) {
                alert('创建失败: ' + error.message);
            } finally {
                isUserInteracting = false; // 用户交互结束
            }
        }

        // 删除文件或文件夹
        async function deleteFile(filePath, fileName, event) {
            event.stopPropagation(); // 阻止事件冒泡

            if (!confirm(`确定要删除 "${fileName}" 吗？此操作不可撤销。`)) {
                return;
            }

            isUserInteracting = true; // 标记用户正在交互

            try {
                const response = await fetch('/api/delete', {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        filePath: filePath
                    })
                });

                const result = await response.json();

                if (response.ok) {
                    alert(result.message);
                    refreshFileList(); // 立即刷新文件列表
                } else {
                    alert('删除失败: ' + result.error);
                }

            } catch (error) {
                alert('删除失败: ' + error.message);
            } finally {
                isUserInteracting = false; // 用户交互结束
            }
        }

        // 回车键创建文件夹
        document.addEventListener('keydown', function (e) {
            if (e.key === 'Enter' && !document.getElementById('createFolderModal').classList.contains('hidden')) {
                createFolder();
            }
            if (e.key === 'Escape') {
                hideCreateFolderModal();
            }
        });
    </script>
</body>

</html>